MongoDB Conditional Queries: Examples from Simple to Complex Queries

This article is an introductory guide to MongoDB conditional queries, explaining screening methods from simple to complex through specific examples. Centering on the `find()` method, with the `users` collection as an example (containing fields such as name, age, hobbies, address, etc.), it covers the following content: 1. **Basic Conditions**: Directly query for equality using key-value pairs, e.g., `{age:25}` to find users aged 25. Nested fields use dot notation (e.g., `address.city`). 2. **Comparison Operators**: Support `$gt` (greater than), `$lt` (less than), `$gte` (≥), `$lte` (≤), `$ne` (≠), e.g., `{age:{$gt:25}}` to find users over 25. 3. **Logical Operators**: Multiple conditions default to `AND`. Use `$or` to combine conditions (e.g., `$or:[{"age":25},{"address.city":"Beijing"}]`), and `$not` to negate conditions (e.g., age ≤ 30). 4. **Array Queries**: `$in` matches array elements (e.g., `hobbies:{$in:["reading","travel"]}`).

Read More